﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace UcAsp.WorkFrame
{
   public  class UcAspWebClient
    {
       public static string GetString(string url)
       {
           WebClient web = new WebClient();
           byte[] webbyte = web.DownloadData(url);
           string str = System.Text.Encoding.UTF8.GetString(webbyte);
           return str;
       }
       public static string GetString(string url,string header)
       {
           WebClient web = new WebClient();
           web.Headers.Add("basic", header);
           
           byte[] webbyte = web.DownloadData(url);
           string str = System.Text.Encoding.UTF8.GetString(webbyte);
           return str;
       }
       public static string PostString(string url, Dictionary<string, string> param)
       {
           string result = string.Empty;
           HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
           req.Method = "POST";
           req.KeepAlive = true;
           req.UserAgent = "UcAspApp2.0";
           req.Timeout = 300000;
           req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

           byte[] postData = Encoding.UTF8.GetBytes(PostData(param));
           Stream reqStream = req.GetRequestStream();
           reqStream.Write(postData, 0, postData.Length);
           reqStream.Close();

           HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
           Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);

           Stream stream = null;
           StreamReader reader = null;

           stream = rsp.GetResponseStream();
           reader = new StreamReader(stream, encoding);

           result = reader.ReadToEnd();

           if (reader != null) reader.Close();
           if (stream != null) stream.Close();
           if (rsp != null) rsp.Close();
           return result;
       }
       protected static string PostData(IDictionary<string, string> parameters)
       {
           StringBuilder postData = new StringBuilder();
           bool hasParam = false;

           IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
           while (dem.MoveNext())
           {
               string name = dem.Current.Key;
               string value = dem.Current.Value;
               // 忽略参数名或参数值为空的参数
               if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
               {
                   if (hasParam)
                   {
                       postData.Append("&");
                   }

                   postData.Append(name);
                   postData.Append("=");
                   postData.Append(Uri.EscapeDataString(value));
                   hasParam = true;
               }
           }

           return postData.ToString();
       }
    }
}
